// 上报内容配置
<template>
  <draggable class="Reported_box my_loading" v-loading="loadingPage">
    <draggable class="iotBox">
      <draggable class="dragDemo">
        <!--列表1-->
        <!-- <draggable class="iot_l">
          <div class="lotl_title">
            上报可选内容
            <div class="num_r">共 {{iolnum_lt}} 项</div>
          </div>
          <div id="dragbtn">
            <draggable class="box_left">
              <el-menu
                background-color="#fff"
                text-color="#000"
                :unique-opened="true"
                style="width: 100%;"
              >
                <el-submenu index="1">
                  <template slot="title">
                    <span class="bgc_title">电能数据</span>
                    <span class="num_box">{{listLeft1.length}} 项</span>
                  </template>
                  <el-menu-item-group>
                    <draggable
                      :class="['list-group',{'noAllowed':isShow}]"
                      element="div"
                      :scroll="true"
                      v-model="listLeft1"
                      :options="dragOptions1"
                      @end="isDragging2"
                    >
                      <div v-for="(item, key) in listLeft1" :key="key" class="box">{{ dnsj[item] }}</div>
                    </draggable>
                  </el-menu-item-group>
                </el-submenu>
                <el-submenu index="2">
                  <template slot="title">
                    <span class="bgc_title">交流通道数据</span>
                    <span class="num_box">{{listLeft2.length}} 项</span>
                  </template>
                  <el-menu-item-group>
                    <draggable
                      :class="['list-group',{'noAllowed':isShow}]"
                      element="div"
                      :scroll="true"
                      v-model="listLeft2"
                      :options="dragOptions2"
                      @end="isDragging2"
                    >
                      <div v-for="(item, key) in listLeft2" :key="key" class="box">{{ Ac[item] }}</div>
                    </draggable>
                  </el-menu-item-group>
                </el-submenu>
                <el-submenu index="3">
                  <template slot="title">
                    <span class="bgc_title">直流通道数据</span>
                    <span class="num_box">{{listLeft3.length}} 项</span>
                  </template>
                  <el-menu-item-group>
                    <draggable
                      :class="['list-group',{'noAllowed':isShow}]"
                      element="div"
                      :scroll="true"
                      v-model="listLeft3"
                      :options="dragOptions3"
                      @end="isDragging2"
                    >
                      <div v-for="(item, key) in listLeft3" :key="key" class="box">{{ Dc[item] }}</div>
                    </draggable>
                  </el-menu-item-group>
                </el-submenu>
                <el-submenu index="4">
                  <template slot="title">
                    <span class="bgc_title">其他数据</span>
                    <span class="num_box">{{listLeft4.length}} 项</span>
                  </template>
                  <el-menu-item-group>
                    <draggable
                      :class="['list-group',{'noAllowed':isShow}]"
                      element="div"
                      :scroll="true"
                      v-model="listLeft4"
                      :options="dragOptions4"
                      @end="isDragging2"
                    >
                      <div v-for="(item, key) in listLeft4" :key="key" class="box">{{ other[item] }}</div>
                    </draggable>
                  </el-menu-item-group>
                </el-submenu>
              </el-menu>
            </draggable>
          </div>
        </draggable>-->
        <!--列表2-->
        <div class="iot_r">
          <div class="lotl_title">
            上报内容
            <div class="num_r">共 {{ iolnum_rt }} 项</div>
            <!-- 上报内容（最多可以上报
            <span style="color:#F56C6C">32</span>项）
            -->
          </div>
          <div class="box_left">
            <el-menu background-color="#fff" text-color="#000" :unique-opened="true" style="width: 100%">
              <el-submenu index="1">
                <template slot="title">
                  <span class="bgc_title">电能数据</span>
                  <span class="num_box">{{ listRight1.length }} 项</span>
                </template>
                <el-menu-item-group>
                  <draggable class="list-group" element="div" :scroll="true" v-model="listRight1" :options="dragOptions5" @start="isDragging" @end="isDragging3">
                    <div v-for="(item, key) in listRight1" :key="key" class="box">{{ dnsj[item] }}</div>
                  </draggable>
                </el-menu-item-group>
              </el-submenu>
              <el-submenu index="2">
                <template slot="title">
                  <span class="bgc_title">交流通道数据</span>
                  <span class="num_box">{{ listRight2.length }} 项</span>
                </template>
                <el-menu-item-group>
                  <draggable class="list-group" element="div" :scroll="true" v-model="listRight2" :options="dragOptions6" @start="isDragging" @end="isDragging3">
                    <div v-for="(item, key) in listRight2" :key="key" class="box">{{ Ac[item] }}</div>
                  </draggable>
                </el-menu-item-group>
              </el-submenu>
              <el-submenu index="3">
                <template slot="title">
                  <span class="bgc_title">直流通道数据</span>
                  <span class="num_box">{{ listRight3.length }} 项</span>
                </template>
                <el-menu-item-group>
                  <draggable class="list-group" element="div" :scroll="true" v-model="listRight3" :options="dragOptions7" @start="isDragging" @end="isDragging3">
                    <div v-for="(item, key) in listRight3" :key="key" class="box">{{ Dc[item] }}</div>
                  </draggable>
                </el-menu-item-group>
              </el-submenu>
              <el-submenu index="4">
                <template slot="title">
                  <span class="bgc_title">其他数据</span>
                  <span class="num_box">{{ listRight4.length }} 项</span>
                </template>
                <el-menu-item-group>
                  <draggable class="list-group" element="div" :scroll="true" v-model="listRight4" :options="dragOptions8" @start="isDragging" @end="isDragging3">
                    <div v-for="(item, key) in listRight4" :key="key" class="box">{{ other[item] }}</div>
                  </draggable>
                </el-menu-item-group>
              </el-submenu>
            </el-menu>
            <!-- <div class="footer_box">
              <el-button
                size="small"
                type="primary"
                :disabled="shangBao"
                @click="reportedData"
                class="btn_box"
                :loading="btnLoad"
              >上报</el-button>
            </div>-->
          </div>
        </div>
      </draggable>
    </draggable>
  </draggable>
</template>
<script>
import draggable from 'vuedraggable' // 引入draggable
import { getUUID, isJSON, errorTips, overTimeTips, intervalTime, send, sendPing, newSocket } from '@/utils/websocket'
// import { tipArr } from '@/utils/tips'
export default {
  name: 'dragDemo',
  components: {
    draggable,
  },
  data: function () {
    return {
      socket: '',
      setIntervalWesocketPush: null,
      sb_bkx: 0,
      sb_bky: 0,
      is_moving: false,
      shangBao: false,
      username: '',
      btnLoad: false,
      timeHandle: '',
      dnsj: {
        R_01010001: '电压',
        R_01010002: '功率',
        R_01010003: '电流',
        R_01010004: '夹角',
        R_01010005: '频率',
        R_01010010: '有功总电能',
      },
      Ac: {
        R_01020015: '交流通道1状态',
        R_01020016: '交流通道2状态',
        R_01020017: '交流通道3状态',
        R_01020018: '交流通道4状态',
        R_010f0005: '交流通道1继电器实际状态',
        R_010f0006: '交流通道2继电器实际状态',
        R_010f0007: '交流通道3继电器实际状态',
        R_010f0008: '交流通道4继电器实际状态',
      },
      Dc: {
        R_01020003: '直流通道1电压',
        R_01020004: '直流通道1电流',
        R_01020005: '直流通道2电压',
        R_01020006: '直流通道2电流',
        R_01020007: '直流通道3电压',
        R_01020008: '直流通道3电流',
        R_01020009: '直流通道4电压',
        R_0102000a: '直流通道4电流',
        R_0102000b: '直流通道5电压',
        R_0102000c: '直流通道5电流',
        R_0102000d: '直流通道6电压',
        R_0102000e: '直流通道6电流',
        R_0102000f: '直流通道1状态',
        R_01020010: '直流通道2状态',
        R_01020011: '直流通道3状态',
        R_01020012: '直流通道4状态',
        R_01020013: '直流通道5状态',
        R_01020014: '直流通道6状态',
      },
      other: {
        R_01020001: '内部温度',
        R_01020002: '电池电压',
        R_01020019: 'Net节点状态',
        R_01050001: '信号强度',
      },
      // 计数
      iolnum_rt: 0, // 右侧上报数量
      iolnum_lt: 0, // 左侧数量
      isShow: false,
      ip: {},
      show1: false,
      show2: false,
      show3: false,
      show4: false,
      show5: false,
      show6: false,
      show7: false,
      show8: false,
      listLeft1: [],
      listLeft2: [],
      listLeft3: [],
      listLeft4: [],
      listRight1: [],
      listRight2: [],
      listRight3: [],
      listRight4: [],
      dialogVisible2: false,
      timerNum: 0,
      num: 0,
      loading: false,
      loadingPage: true,
      timer: null,
      Movetimer: null,
    }
  },
  watch: {
    iolnum_rt: {
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal >= 32) {
          this.isShow = true
          this.shangBao = false
        }
      },
    },
  },
  computed: {
    // 判断上报按钮
    dragOptions1: {
      get: function () {
        return {
          animation: 0,
          group: {
            name: 'description',
            pull: true,
          },
          ghostClass: 'ghost',
          // disabled: true,
          disabled: this.isShow,
          scroll: true,
          fallbackClass: true,
        }
      },
    },
    dragOptions2: function () {
      return {
        animation: 0,
        group: {
          name: 'description2',
          pull: true,
        },
        ghostClass: 'ghost',
        disabled: this.isShow,
        scroll: true,
        fallbackClass: true,
      }
    },
    dragOptions3: function () {
      return {
        animation: 0,
        group: {
          name: 'description3',
          pull: true,
        },
        ghostClass: 'ghost',
        disabled: this.isShow,
        scroll: true,
        fallbackClass: true,
      }
    },
    dragOptions4: function () {
      return {
        animation: 0,
        group: {
          name: 'description4',
          pull: true,
        },
        ghostClass: 'ghost',
        disabled: this.isShow,
        scroll: true,
        fallbackClass: true,
      }
    },
    // 右侧规则
    dragOptions5: function () {
      return {
        animation: 0,
        group: 'description',
      }
    },
    dragOptions6: function () {
      return {
        animation: 0,
        group: 'description2',
      }
    },
    dragOptions7: function () {
      return {
        animation: 0,
        group: 'description3',
      }
    },
    dragOptions8: function () {
      return {
        animation: 0,
        group: 'description4',
      }
    },
    // ,
    // computedMessage() {
    //   return this.listRight1.length + this.listRight2.length + this.listRight3.length + this.listRight4.length
    // }
  },
  created: function () {
    this.UUID = getUUID(32, 16)
    for (const k in this.dnsj) {
      this.listLeft1.push(k)
    }
    for (const k in this.Ac) {
      this.listLeft2.push(k)
    }
    for (const k in this.Dc) {
      this.listLeft3.push(k)
    }
    for (const k in this.other) {
      this.listLeft4.push(k)
    }
    this.username = localStorage.getItem('userName') // 用户登录名
    this.createSocket() // websocket
    if (this.loadingPage) {
      this.timer = setTimeout(() => {
        this.loadingPage = false
        this.$message.error(overTimeTips)
      }, intervalTime)
    } else {
      clearTimeout(this.timer)
    }
    this.iolnum_lt = this.listLeft1.length + this.listLeft2.length + this.listLeft3.length + this.listLeft4.length // 初始左侧数量
  },
  mounted: function () {
    // 为了防止火狐浏览器拖拽的时候以新标签打开，此代码真实有效
    document.body.ondrop = function (event) {
      event.preventDefault()
      event.stopPropagation()
    }
  },
  methods: {
    // 建立websocket连接
    createSocket() {
      // // 在main.js或需要使用的地方引入并建立连接
      this.socket && this.socket.close()
      if (!this.socket) {
        console.log('建立websocket连接')
        this.socket = new WebSocket(newSocket(this.username, this.UUID))
        this.socket.onopen = this.open
        this.socket.onmessage = this.getMessage
        this.socket.onerror = this.onerror
        this.socket.onclose = this.onclose
      } else {
        console.log('websocket已连接')
      }
    },
    open() {
      const list = [
        {
          command_id: '00110001',
          value: '',
        },
      ]
      send(this, '01', list) // 上报内容
      sendPing(this) // 发送心跳
    },
    getMessage: function (msg) {
      switch (isJSON(msg.data)) {
        case false: // 主板实时数据
          break
        case true:
          // 接收到消息回复ok
          var SN = localStorage.getItem('SN')
          this.socket.send(`TILL${SN}OK`)
          if (typeof JSON.parse(msg.data) === 'object' && 'obj') {
            const res = JSON.parse(msg.data)
            switch (Number(res.doing)) {
              case 1: // 读取数据
                // 状态码错误提示
                console.log('上报内容配置-收到信息', res)
                if (res.host_status !== '0000') {
                  // errorTips(res.host_status)
                  errorTips(res.host_status, res.tips)
                  this.loadingPage = false // 取消数据加载中样式
                  clearTimeout(this.timer)
                  this.btnLoad = false // 上报按钮样式
                  return
                }
                // // 接收到消息回复ok
                // var SN = localStorage.getItem('SN')
                // this.socket.send(`TILL${SN}OK`)
                if (res.list.length > 0) {
                  for (let i = 0; i < res.list.length; i++) {
                    // var id = res.list[i].command_id.toLowerCase()
                    var content = res.list[i].value.split('_')
                    // console.log(id, content)
                    // console.log('上报内容配置-写入信息:', msg.data)
                    // var content = getStr(msg.data, '>', '').split('_')
                    // console.log(getStr(msg.data, '>', '').split('_'))
                    var arr1 = []
                    var arr2 = []
                    var arr3 = []
                    var arr4 = []
                    for (let i = 0; i < content.length; i++) {
                      for (let j = 0; j < this.listLeft1.length; j++) {
                        if (content[i].toLowerCase() === this.listLeft1[j].replace('R_', '')) {
                          // 电能数据
                          arr1.push('R_' + content[i].toLowerCase())
                        }
                      }
                      for (let j = 0; j < this.listLeft2.length; j++) {
                        if (content[i].toLowerCase() === this.listLeft2[j].replace('R_', '')) {
                          // 电能数据
                          arr2.push('R_' + content[i].toLowerCase())
                        }
                      }
                      for (let j = 0; j < this.listLeft3.length; j++) {
                        if (content[i].toLowerCase() === this.listLeft3[j].replace('R_', '')) {
                          // 电能数据
                          arr3.push('R_' + content[i].toLowerCase())
                        }
                      }
                      for (let j = 0; j < this.listLeft4.length; j++) {
                        if (content[i].toLowerCase() === this.listLeft4[j].replace('R_', '')) {
                          // 电能数据
                          arr4.push('R_' + content[i].toLowerCase())
                        }
                      }
                    }
                    this.listLeft1 = this.getArrDifference(arr1, this.listLeft1)
                    this.listLeft2 = this.getArrDifference(arr2, this.listLeft2)
                    this.listLeft3 = this.getArrDifference(arr3, this.listLeft3)
                    this.listLeft4 = this.getArrDifference(arr4, this.listLeft4)
                    this.listRight1 = arr1
                    this.listRight2 = arr2
                    this.listRight3 = arr3
                    this.listRight4 = arr4
                    this.iolnum_rt = this.listRight1.length + this.listRight2.length + this.listRight3.length + this.listRight4.length // 右侧上报数量
                    this.iolnum_lt = this.listLeft1.length + this.listLeft2.length + this.listLeft3.length + this.listLeft4.length // 左侧数量
                    this.loading = false // 取消上报数据加载中样式
                  }
                }
                this.loadingPage = false // 取消数据加载中样式
                break
              case 2: // 写入数据
                console.log('02上报内容配置', res)
                if (res.host_status !== '0000') {
                  // errorTips(res.host_status)
                  errorTips(res.host_status, res.tips)
                  this.btnLoad = false // 上报按钮样式
                  return
                }
                this.btnLoad = false // 上报按钮样式
                this.$message.success('修改成功')
                break
              default:
            }
            clearTimeout(this.timer)
          }
          break
        default:
      }
    },
    getArrDifference(arr1, arr2) {
      return arr1.concat(arr2).filter(function (v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v)
      })
    },
    // 左侧放到右侧
    isDragging2(e) {
      // console.log(this.tipsFlag)
      // if (this.tipsFlag) {
      //   this.$message.error('只能上报30项')
      //   return
      // }
      if (!e.pullMode) {
        // 提醒消息
        this.$message.error('请选择正确上报区域')
      }
      this.iolnum_rt = this.listRight1.length + this.listRight2.length + this.listRight3.length + this.listRight4.length
      if (this.iolnum_rt >= 32) {
        this.isShow = true
      }
    },
    // 右侧放到左侧
    isDragging(e) {
      this.iolnum_rt = this.listRight1.length + this.listRight2.length + this.listRight3.length + this.listRight4.length
      if (this.iolnum_rt >= 32) {
        this.isShow = false
      }
    },
    isDragging3(e) {
      if (!e.pullMode) {
        this.$message({
          showClose: true,
          message: '请选择正确的区域',
          type: 'error',
        })
      }
    },
    reportedData: function () {
      // 先清除上一次定时器
      if (this.timeHandle) {
        clearTimeout(this.timeHandle) // 清除定时器
        this.timeHandle = null
      }
      this.btnLoad = true
      const arr = []
      if (this.listRight1.length > 0) {
        for (let i = 0; i < this.listRight1.length; i++) {
          arr.push(this.listRight1[i].replace('R_', ''))
        }
      }
      if (this.listRight2.length > 0) {
        for (let i = 0; i < this.listRight2.length; i++) {
          arr.push(this.listRight2[i].replace('R_', ''))
        }
      }
      if (this.listRight3.length > 0) {
        for (let i = 0; i < this.listRight3.length; i++) {
          arr.push(this.listRight3[i].replace('R_', ''))
        }
      }
      if (this.listRight4.length > 0) {
        for (let i = 0; i < this.listRight4.length; i++) {
          arr.push(this.listRight4[i].replace('R_', ''))
        }
      }
      const list = [
        {
          command_id: '00110001',
          value: arr.join('_'),
        },
      ]
      // console.log(list)
      send(this, '02', list)
      this.timeHandle = setTimeout(() => {
        if (this.btnLoad) {
          this.btnLoad = false
          this.$message({
            showClose: true,
            message: '修改失败 稍后重试',
            type: 'error',
          })
        }
      }, intervalTime)
    },
    onerror(e) {
      this.socket.close()
      clearInterval(this.setIntervalWesocketPush)
      console.log('连接失败')
    },
    onclose(e) {
      clearInterval(this.setIntervalWesocketPush)
      console.log('websocket已断开')
      this.loading = false
      this.$message.error('websocket已断开')
    },
  },
  destroyed: function () {
    this.socket.send('CLOSE>-<' + this.username) // 关闭页面前发送
    // 销毁监听
    clearInterval(this.setIntervalWesocketPush)
    this.socket.onclose = this.socket.close()
  },
}
</script>

<style lang="scss" scoped>
/* 上报样式 */
.el-submenu {
  border-bottom: 1.5px solid #ebeef5;
  border-right: none;
}
.Reported_box {
  padding: 15px;
  // background-color: #f8f8f8;
  .iotBox {
    height: 800px;
    background-color: #fff;
    padding: 0 15px;
    .iot_l {
      width: 883px;
      height: 762px;
      margin-right: 90px;
    }
    .iot_r {
      position: relative;
      width: 883px;
      height: 775px;
      margin-right: 90px;
      .footer_box {
        position: absolute;
        bottom: 0;
        width: 100%;
        height: 50px;
        line-height: 50px;
        text-align: center;
        border-top: 1px solid rgba(220, 223, 230, 1);
        .btn_box {
          width: 88px;
        }
      }
    }
    .list-group {
      padding: 8px 8px;
      // display: flex;
      // flex-wrap: wrap;
      // justify-content: space-between;
      // height: 290px;
      // height: auto;
      min-height: 70px;
      overflow: hidden;
      background-color: #f6faff;
      > div {
        float: left;
        margin: 5px;
        width: 208px;
        height: 30px;
        line-height: 30px;
        color: #409eff;
        background-color: #ecf5ff;
        border: 1px dashed #bbddff;
        cursor: pointer;
        text-align: center;
        font-size: 14px;
        font-weight: 400;
        padding: 7px 0;
      }
      &.noAllowed {
        cursor: not-allowed;
        > div {
          cursor: not-allowed;
        }
      }
    }
  }
  .dragDemo {
    display: flex;
    color: #555;
    .bgc_title {
      position: absolute;
    }
    .bgc {
      position: absolute;
      left: 0;
      height: 100%;
      width: 100%;
      background-color: #ebf5fd;
      border-bottom: 1px solid #d3e6fa;
      z-index: 0;
    }
    .num_box {
      color: #909399;
      font-size: 12px;
      position: absolute;
      right: 45px;
      .inputITem {
        color: #909399;
        background: none;
        outline: none;
        border: none;
        width: 16px;
        padding-bottom: 3px;
        vertical-align: middle;
      }
    }
    .lotl_title {
      position: relative;
      font-size: 14px;
      color: #101010;
      height: 55px;
      line-height: 65px;
      display: flex;
      justify-content: center;
      .num_r {
        position: absolute;
        right: 15px;
        color: #1989fa;
        font-size: 14px;
        .input {
          color: #909399;
          background: none;
          outline: none;
          border: none;
          width: 16px;
        }
      }
    }
    .box_left {
      border: 1.5px solid rgba(220, 223, 230, 1);
      height: 762px - 42px;
    }
  }
}
::v-deep .is-opened .el-submenu__title {
  background-color: #ecf5ff !important;
}
</style>
